{% extends "members/base.html" %}

{% block title %}发布详情{% endblock %}

{% block extra_css %}
<style>
.detail-card {
    border: none;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    border-radius: 8px;
}

.stats-card {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border-radius: 12px;
    padding: 1.5rem;
}

.stats-number {
    font-size: 2rem;
    font-weight: bold;
    margin-bottom: 0.5rem;
}

.stats-label {
    font-size: 0.9rem;
    opacity: 0.9;
}

.assessment-card {
    border: 1px solid #e0e0e0;
    border-radius: 8px;
    transition: all 0.3s ease;
}

.assessment-card:hover {
    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
    transform: translateY(-2px);
}

.score-badge {
    font-size: 1.1rem;
    padding: 0.5rem 1rem;
    border-radius: 20px;
}

.chart-container {
    position: relative;
    height: 300px;
    margin: 1rem 0;
}

.filter-tabs {
    border-bottom: 2px solid #f8f9fa;
    margin-bottom: 1.5rem;
}

.filter-tab {
    padding: 0.75rem 1.5rem;
    border: none;
    background: none;
    color: #6c757d;
    border-bottom: 2px solid transparent;
    transition: all 0.3s ease;
}

.filter-tab.active {
    color: #007bff;
    border-bottom-color: #007bff;
}

.filter-tab:hover {
    color: #007bff;
    background: #f8f9fa;
}

.export-section {
    background: #f8f9fa;
    border-radius: 8px;
    padding: 1rem;
    margin-top: 1.5rem;
}

.link-section {
    background: #e3f2fd;
    border: 1px solid #bbdefb;
    border-radius: 8px;
    padding: 1rem;
}

@media (max-width: 768px) {
    .stats-number {
        font-size: 1.5rem;
    }
    
    .chart-container {
        height: 250px;
    }
    
    .filter-tabs {
        overflow-x: auto;
        white-space: nowrap;
    }
}
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- 页面标题 -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h2><i class="bi bi-eye me-2"></i>发布详情</h2>
            <p class="text-muted mb-0">查看发布的详细信息和测评数据</p>
        </div>
        <a href="{{ url_for('members.scale_publications') }}" class="btn btn-outline-secondary">
            <i class="bi bi-arrow-left me-2"></i>返回发布管理
        </a>
    </div>

    <!-- 发布信息卡片 -->
    <div class="card detail-card mb-4">
        <div class="card-body">
            <div class="row">
                <div class="col-md-8">
                    <h5 class="card-title mb-3" id="publication-title">-</h5>
                    <p class="text-muted mb-3" id="publication-description">-</p>
                    
                    <div class="row mb-3">
                        <div class="col-sm-6">
                            <strong>原量表：</strong>
                            <span id="original-scale-title">-</span>
                        </div>
                        <div class="col-sm-6">
                            <strong>发布状态：</strong>
                            <span id="publication-status">-</span>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-sm-6">
                            <strong>创建时间：</strong>
                            <span id="created-time">-</span>
                        </div>
                        <div class="col-sm-6">
                            <strong>最后访问：</strong>
                            <span id="last-access-time">-</span>
                        </div>
                    </div>
                </div>
                
                <div class="col-md-4">
                    <div class="link-section">
                        <h6><i class="bi bi-link-45deg me-2"></i>公开访问链接</h6>
                        <div class="input-group mb-2">
                            <input type="text" class="form-control" id="public-url" readonly>
                            <button class="btn btn-outline-primary" onclick="copyLink()">
                                <i class="bi bi-clipboard"></i>
                            </button>
                        </div>
                        <div class="d-grid gap-2">
                            <button class="btn btn-sm btn-primary" onclick="openLink()">
                                <i class="bi bi-box-arrow-up-right me-1"></i>打开链接
                            </button>
                            <button class="btn btn-sm btn-outline-secondary" onclick="editPublication()">
                                <i class="bi bi-pencil me-1"></i>编辑发布
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 统计概览 -->
    <div class="row mb-4">
        <div class="col-md-3 col-sm-6 mb-3">
            <div class="stats-card">
                <div class="stats-number" id="total-access">-</div>
                <div class="stats-label">总访问量</div>
            </div>
        </div>
        <div class="col-md-3 col-sm-6 mb-3">
            <div class="stats-card">
                <div class="stats-number" id="total-assessments">-</div>
                <div class="stats-label">总测评数</div>
            </div>
        </div>
        <div class="col-md-3 col-sm-6 mb-3">
            <div class="stats-card">
                <div class="stats-number" id="conversion-rate">-</div>
                <div class="stats-label">转化率</div>
            </div>
        </div>
        <div class="col-md-3 col-sm-6 mb-3">
            <div class="stats-card">
                <div class="stats-number" id="avg-score">-</div>
                <div class="stats-label">平均分数</div>
            </div>
        </div>
    </div>

    <!-- 数据分析 -->
    <div class="card detail-card mb-4">
        <div class="card-header">
            <h6 class="mb-0"><i class="bi bi-bar-chart me-2"></i>数据分析</h6>
        </div>
        <div class="card-body">
            <!-- 图表筛选 -->
            <div class="filter-tabs">
                <button class="filter-tab active" onclick="switchChart('trend')">
                    <i class="bi bi-graph-up me-1"></i>访问趋势
                </button>
                <button class="filter-tab" onclick="switchChart('score')">
                    <i class="bi bi-bar-chart me-1"></i>分数分布
                </button>
                <button class="filter-tab" onclick="switchChart('duration')">
                    <i class="bi bi-clock me-1"></i>完成时长
                </button>
                <button class="filter-tab" onclick="switchChart('demographics')">
                    <i class="bi bi-people me-1"></i>用户画像
                </button>
            </div>
            
            <!-- 图表容器 -->
            <div class="chart-container">
                <canvas id="data-chart"></canvas>
            </div>
            
            <!-- 图表说明 -->
            <div class="text-center text-muted" id="chart-description">
                显示最近30天的访问和测评趋势
            </div>
        </div>
    </div>

    <!-- 测评记录 -->
    <div class="card detail-card">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h6 class="mb-0"><i class="bi bi-list-ul me-2"></i>测评记录</h6>
            <div>
                <select class="form-select form-select-sm" id="status-filter" onchange="loadAssessments()">
                    <option value="">全部状态</option>
                    <option value="completed">已完成</option>
                    <option value="in_progress">进行中</option>
                    <option value="abandoned">已放弃</option>
                </select>
            </div>
        </div>
        <div class="card-body">
            <!-- 测评记录列表 -->
            <div id="assessments-container">
                <!-- 测评记录将通过JavaScript动态加载 -->
            </div>
            
            <!-- 分页 -->
            <nav aria-label="测评记录分页" id="assessments-pagination" class="mt-3">
                <!-- 分页将通过JavaScript动态生成 -->
            </nav>
        </div>
    </div>

    <!-- 导出数据 -->
    <div class="export-section">
        <h6><i class="bi bi-download me-2"></i>数据导出</h6>
        <p class="text-muted mb-3">导出测评数据进行进一步分析</p>
        <div class="row">
            <div class="col-md-6 mb-2">
                <button class="btn btn-outline-success w-100" onclick="exportData('excel')">
                    <i class="bi bi-file-earmark-excel me-2"></i>导出为 Excel
                </button>
            </div>
            <div class="col-md-6 mb-2">
                <button class="btn btn-outline-info w-100" onclick="exportData('csv')">
                    <i class="bi bi-file-earmark-text me-2"></i>导出为 CSV
                </button>
            </div>
        </div>
    </div>

    <!-- 加载状态 -->
    <div class="text-center py-5 d-none" id="loading-indicator">
        <div class="spinner-border text-primary" role="status">
            <span class="visually-hidden">加载中...</span>
        </div>
        <p class="mt-2 text-muted">正在加载数据...</p>
    </div>
</div>

<!-- 编辑发布模态框 -->
<div class="modal fade" id="editModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">编辑发布信息</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="edit-form">
                    <div class="mb-3">
                        <label class="form-label">自定义标题</label>
                        <input type="text" class="form-control" id="edit-title" maxlength="200">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">自定义描述</label>
                        <textarea class="form-control" id="edit-description" rows="3" maxlength="500"></textarea>
                    </div>
                    <div class="mb-3">
                        <div class="form-check form-switch">
                            <input class="form-check-input" type="checkbox" id="edit-active">
                            <label class="form-check-label" for="edit-active">
                                启用发布
                            </label>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="saveEdit()">保存</button>
            </div>
        </div>
    </div>
</div>

<!-- 复制成功提示 -->
<div class="toast-container position-fixed bottom-0 end-0 p-3">
    <div id="copy-toast" class="toast" role="alert">
        <div class="toast-header">
            <i class="bi bi-check-circle-fill text-success me-2"></i>
            <strong class="me-auto">复制成功</strong>
            <button type="button" class="btn-close" data-bs-dismiss="toast"></button>
        </div>
        <div class="toast-body">
            链接已复制到剪贴板
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<!-- Chart.js CDN -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<script>
const publicationId = {{ publication_id }};
let currentChart = null;
let currentChartType = 'trend';
let assessmentPage = 1;
let publicationData = null;

// 页面加载时初始化
document.addEventListener('DOMContentLoaded', function() {
    loadPublicationDetail();
    loadAssessments();
});

// 加载发布详情
function loadPublicationDetail() {
    document.getElementById('loading-indicator').classList.remove('d-none');
    
    apiRequest(`/api/members/scale-publications/${publicationId}/detail`)
        .then(response => {
            if (response.code === 200) {
                publicationData = response.data;
                displayPublicationDetail(publicationData);
                loadChartData('trend');
            } else {
                throw new Error(response.message || '加载失败');
            }
        })
        .catch(error => {
            console.error('加载发布详情失败:', error);
            showResult(false, '加载发布详情失败: ' + error.message);
        })
        .finally(() => {
            document.getElementById('loading-indicator').classList.add('d-none');
        });
}

// 显示发布详情
function displayPublicationDetail(data) {
    document.getElementById('publication-title').textContent = data.custom_title || data.scale.title;
    document.getElementById('publication-description').textContent = data.custom_description || data.scale.description || '暂无描述';
    document.getElementById('original-scale-title').textContent = data.scale.title;
    document.getElementById('publication-status').innerHTML = data.is_active ? 
        '<span class="badge bg-success">活跃</span>' : 
        '<span class="badge bg-secondary">已停用</span>';
    document.getElementById('created-time').textContent = formatDate(data.created_at);
    document.getElementById('last-access-time').textContent = data.last_accessed_at ? 
        formatDate(data.last_accessed_at) : '从未访问';
    document.getElementById('public-url').value = data.public_url;
    
    // 更新统计数据
    document.getElementById('total-access').textContent = data.access_count;
    document.getElementById('total-assessments').textContent = data.assessment_count;
    document.getElementById('conversion-rate').textContent = data.access_count > 0 ? 
        Math.round((data.assessment_count / data.access_count) * 100) + '%' : '0%';
    
    // 平均分数需要从测评记录中计算
    calculateAverageScore();
}

// 计算平均分数
function calculateAverageScore() {
    apiRequest(`/api/members/scale-publications/${publicationId}/assessments?per_page=1000&status=completed`)
        .then(response => {
            if (response.code === 200 && response.data.statistics) {
                const avgScore = response.data.statistics.average_score;
                document.getElementById('avg-score').textContent = avgScore ? avgScore.toFixed(1) : '0';
            }
        })
        .catch(error => {
            console.error('计算平均分数失败:', error);
            document.getElementById('avg-score').textContent = '0';
        });
}

// 加载测评记录
function loadAssessments(page = 1) {
    assessmentPage = page;
    const statusFilter = document.getElementById('status-filter').value;
    
    const params = new URLSearchParams({
        page: page,
        per_page: 10
    });
    
    if (statusFilter) {
        params.append('status', statusFilter);
    }
    
    apiRequest(`/api/members/scale-publications/${publicationId}/assessments?${params.toString()}`)
        .then(response => {
            if (response.code === 200) {
                displayAssessments(response.data.assessments);
                updateAssessmentsPagination(response.data.pagination);
            } else {
                throw new Error(response.message || '加载失败');
            }
        })
        .catch(error => {
            console.error('加载测评记录失败:', error);
            document.getElementById('assessments-container').innerHTML = 
                '<div class="text-center text-muted py-3">加载测评记录失败</div>';
        });
}

// 显示测评记录
function displayAssessments(assessments) {
    const container = document.getElementById('assessments-container');
    
    if (assessments.length === 0) {
        container.innerHTML = '<div class="text-center text-muted py-3">暂无测评记录</div>';
        return;
    }
    
    container.innerHTML = assessments.map(assessment => `
        <div class="assessment-card p-3 mb-3">
            <div class="row align-items-center">
                <div class="col-md-3">
                    <div class="d-flex align-items-center">
                        <div class="me-3">
                            <i class="bi bi-person-circle display-6 text-muted"></i>
                        </div>
                        <div>
                            <div class="fw-bold">测评者 #${assessment.id}</div>
                            <small class="text-muted">
                                ${assessment.user_info ? 
                                    `${assessment.user_info.age || '未知'}岁 ${assessment.user_info.gender || ''}` : 
                                    '匿名用户'}
                            </small>
                        </div>
                    </div>
                </div>
                
                <div class="col-md-2 text-center">
                    <span class="badge ${getStatusBadgeClass(assessment.status)}">
                        ${getStatusText(assessment.status)}
                    </span>
                </div>
                
                <div class="col-md-2 text-center">
                    ${assessment.total_score !== null ? 
                        `<span class="score-badge bg-primary text-white">${assessment.total_score}</span>` : 
                        '<span class="text-muted">-</span>'}
                </div>
                
                <div class="col-md-2 text-center">
                    <small class="text-muted">
                        ${assessment.duration ? formatDuration(assessment.duration) : '-'}
                    </small>
                </div>
                
                <div class="col-md-3 text-end">
                    <small class="text-muted d-block">
                        ${formatDate(assessment.created_at)}
                    </small>
                    ${assessment.completed_at ? 
                        `<small class="text-success d-block">完成于 ${formatDate(assessment.completed_at)}</small>` : 
                        ''}
                </div>
            </div>
        </div>
    `).join('');
}

// 更新测评记录分页
function updateAssessmentsPagination(pagination) {
    const container = document.getElementById('assessments-pagination');
    
    if (pagination.pages <= 1) {
        container.innerHTML = '';
        return;
    }
    
    let paginationHtml = '<ul class="pagination justify-content-center">';
    
    // 上一页
    paginationHtml += `
        <li class="page-item ${assessmentPage === 1 ? 'disabled' : ''}">
            <a class="page-link" href="#" onclick="loadAssessments(${assessmentPage - 1})">
                <i class="bi bi-chevron-left"></i>
            </a>
        </li>
    `;
    
    // 页码
    for (let i = 1; i <= pagination.pages; i++) {
        if (i === 1 || i === pagination.pages || (i >= assessmentPage - 2 && i <= assessmentPage + 2)) {
            paginationHtml += `
                <li class="page-item ${i === assessmentPage ? 'active' : ''}">
                    <a class="page-link" href="#" onclick="loadAssessments(${i})">${i}</a>
                </li>
            `;
        } else if (i === assessmentPage - 3 || i === assessmentPage + 3) {
            paginationHtml += '<li class="page-item disabled"><span class="page-link">...</span></li>';
        }
    }
    
    // 下一页
    paginationHtml += `
        <li class="page-item ${assessmentPage === pagination.pages ? 'disabled' : ''}">
            <a class="page-link" href="#" onclick="loadAssessments(${assessmentPage + 1})">
                <i class="bi bi-chevron-right"></i>
            </a>
        </li>
    `;
    
    paginationHtml += '</ul>';
    container.innerHTML = paginationHtml;
}

// 切换图表
function switchChart(chartType) {
    currentChartType = chartType;
    
    // 更新标签页状态
    document.querySelectorAll('.filter-tab').forEach(tab => {
        tab.classList.remove('active');
    });
    event.target.classList.add('active');
    
    // 加载对应的图表数据
    loadChartData(chartType);
}

// 加载图表数据
function loadChartData(chartType) {
    // 这里应该调用相应的API获取图表数据
    // 为了演示，我们使用模拟数据
    const mockData = generateMockChartData(chartType);
    renderChart(chartType, mockData);
    
    // 更新图表说明
    const descriptions = {
        'trend': '显示最近30天的访问和测评趋势',
        'score': '显示测评分数的分布情况',
        'duration': '显示测评完成时长的分布',
        'demographics': '显示测评用户的年龄和性别分布'
    };
    
    document.getElementById('chart-description').textContent = descriptions[chartType];
}

// 生成模拟图表数据
function generateMockChartData(chartType) {
    switch (chartType) {
        case 'trend':
            return {
                labels: Array.from({length: 30}, (_, i) => {
                    const date = new Date();
                    date.setDate(date.getDate() - 29 + i);
                    return date.toLocaleDateString('zh-CN', {month: '2-digit', day: '2-digit'});
                }),
                datasets: [
                    {
                        label: '访问量',
                        data: Array.from({length: 30}, () => Math.floor(Math.random() * 20)),
                        borderColor: '#007bff',
                        backgroundColor: 'rgba(0, 123, 255, 0.1)',
                        tension: 0.4
                    },
                    {
                        label: '测评数',
                        data: Array.from({length: 30}, () => Math.floor(Math.random() * 15)),
                        borderColor: '#28a745',
                        backgroundColor: 'rgba(40, 167, 69, 0.1)',
                        tension: 0.4
                    }
                ]
            };
        case 'score':
            return {
                labels: ['0-20', '21-40', '41-60', '61-80', '81-100'],
                datasets: [{
                    label: '人数',
                    data: [5, 12, 25, 18, 8],
                    backgroundColor: [
                        '#dc3545', '#fd7e14', '#ffc107', '#28a745', '#007bff'
                    ]
                }]
            };
        case 'duration':
            return {
                labels: ['<2分钟', '2-5分钟', '5-10分钟', '10-15分钟', '>15分钟'],
                datasets: [{
                    label: '人数',
                    data: [8, 22, 35, 15, 5],
                    backgroundColor: '#007bff'
                }]
            };
        case 'demographics':
            return {
                labels: ['18-25岁', '26-35岁', '36-45岁', '46-55岁', '55岁以上'],
                datasets: [
                    {
                        label: '男性',
                        data: [12, 18, 15, 8, 3],
                        backgroundColor: '#007bff'
                    },
                    {
                        label: '女性',
                        data: [15, 22, 18, 10, 5],
                        backgroundColor: '#e83e8c'
                    }
                ]
            };
        default:
            return null;
    }
}

// 渲染图表
function renderChart(chartType, data) {
    const ctx = document.getElementById('data-chart').getContext('2d');
    
    // 销毁现有图表
    if (currentChart) {
        currentChart.destroy();
    }
    
    const chartConfig = {
        type: chartType === 'trend' ? 'line' : 'bar',
        data: data,
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'top'
                }
            },
            scales: chartType === 'trend' ? {
                y: {
                    beginAtZero: true
                }
            } : {}
        }
    };
    
    if (chartType === 'score' || chartType === 'duration') {
        chartConfig.type = 'doughnut';
        chartConfig.options.scales = {};
    }
    
    currentChart = new Chart(ctx, chartConfig);
}

// 复制链接
function copyLink() {
    const url = document.getElementById('public-url').value;
    navigator.clipboard.writeText(url).then(() => {
        const toast = new bootstrap.Toast(document.getElementById('copy-toast'));
        toast.show();
    }).catch(err => {
        console.error('复制失败:', err);
    });
}

// 打开链接
function openLink() {
    const url = document.getElementById('public-url').value;
    window.open(url, '_blank');
}

// 编辑发布
function editPublication() {
    if (!publicationData) return;
    
    document.getElementById('edit-title').value = publicationData.custom_title || '';
    document.getElementById('edit-description').value = publicationData.custom_description || '';
    document.getElementById('edit-active').checked = publicationData.is_active;
    
    const modal = new bootstrap.Modal(document.getElementById('editModal'));
    modal.show();
}

// 保存编辑
function saveEdit() {
    const data = {
        custom_title: document.getElementById('edit-title').value.trim() || null,
        custom_description: document.getElementById('edit-description').value.trim() || null,
        is_active: document.getElementById('edit-active').checked
    };
    
    apiRequest(`/api/members/scale-publications/${publicationId}`, {
        method: 'PUT',
        body: JSON.stringify(data)
    })
    .then(response => {
        if (response.code === 200) {
            showResult(true, '更新成功', () => {
                const modal = bootstrap.Modal.getInstance(document.getElementById('editModal'));
                modal.hide();
                loadPublicationDetail();
            });
        } else {
            throw new Error(response.message || '更新失败');
        }
    })
    .catch(error => {
        console.error('更新失败:', error);
        showResult(false, '更新失败: ' + error.message);
    });
}

// 导出数据
function exportData(format) {
    // TODO: 实现导出功能
    showResult(false, '导出功能暂未实现，敬请期待');
    return;
    
    const url = `/api/members/scale-publications/${publicationId}/export?format=${format}`;
    
    // 创建隐藏的下载链接
    const link = document.createElement('a');
    link.href = url;
    link.download = `publication_${publicationId}_data.${format}`;
    link.style.display = 'none';
    
    // 添加认证头
    const userToken = localStorage.getItem('userToken');
    if (userToken) {
        // 对于文件下载，我们需要使用不同的方法
        fetch(url, {
            headers: {
                'Authorization': 'Bearer ' + userToken
            }
        })
        .then(response => response.blob())
        .then(blob => {
            const url = window.URL.createObjectURL(blob);
            link.href = url;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            window.URL.revokeObjectURL(url);
        })
        .catch(error => {
            console.error('导出失败:', error);
            showResult(false, '导出失败: ' + error.message);
        });
    }
}

// 工具函数
function getStatusBadgeClass(status) {
    const classes = {
        'completed': 'bg-success',
        'in_progress': 'bg-warning',
        'abandoned': 'bg-secondary'
    };
    return classes[status] || 'bg-secondary';
}

function getStatusText(status) {
    const texts = {
        'completed': '已完成',
        'in_progress': '进行中',
        'abandoned': '已放弃'
    };
    return texts[status] || '未知';
}

function formatDuration(seconds) {
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = seconds % 60;
    return `${minutes}分${remainingSeconds}秒`;
}

function formatDate(dateString) {
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
    });
}
</script>
{% endblock %}